const app = getApp()
const { put, upload } = require('../../utils/request')

// 性别映射关系
const GENDER_MAP = {
  '男': 'male',
  '女': 'female',
  '其他': 'other'
}

const GENDER_MAP_REVERSE = {
  'male': '男',
  'female': '女',
  'other': '其他'
}

Page({
  data: {
    userInfo: {},
    genders: ['男', '女', '其他'],
    genderIndex: 0,
    goals: ['减重', '增肌', '保持健康'],
    goalIndex: 0,
    dietaryRestrictions: [
      { label: '无麸质', value: 'gluten-free', checked: false },
      { label: '素食', value: 'vegetarian', checked: false },
      { label: '无乳糖', value: 'lactose-free', checked: false },
      { label: '无坚果', value: 'nut-free', checked: false }
    ]
  },

  onLoad() {
    const app = getApp()
    const userInfo = app.globalData.userInfo || {}
    console.log(userInfo)
    // 转换后端性别值为前端显示值
    if (userInfo && userInfo.gender) {
      userInfo.gender = GENDER_MAP_REVERSE[userInfo.gender] || '其他'
    }
    
    // 设置性别索引
    const genderIndex = this.data.genders.findIndex(g => g === userInfo.gender)
    
    // 设置目标索引
    const goalIndex = this.data.goals.findIndex(g => g === userInfo.goal)
    
    // 设置饮食限制
    const dietaryRestrictions = this.data.dietaryRestrictions.map(item => ({
      ...item,
      checked: userInfo.dietaryRestrictions?.includes(item.value) || false
    }))
    
    this.setData({
      userInfo,
      genderIndex: genderIndex > -1 ? genderIndex : 0,
      goalIndex: goalIndex > -1 ? goalIndex : 0,
      dietaryRestrictions
    })
  },

  async chooseAvatar() {
    try {
      const res = await wx.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera']
      })

      wx.showLoading({ title: '上传中...' })

      const result = await upload('/upload/avatar', res.tempFilePaths[0])
      
      if (result.code === 0) {
        this.setData({
          'userInfo.avatar': result.url
        })
        wx.showToast({
          title: '上传成功',
          icon: 'success'
        })
      } else {
        throw new Error(result.message)
      }

      wx.hideLoading()
    } catch (error) {
      wx.hideLoading()
      wx.showToast({
        title: error.message || '上传头像失败',
        icon: 'none'
      })
    }
  },

  onNicknameInput(e) {
    this.setData({
      'userInfo.nickname': e.detail.value
    })
  },

  onGenderChange(e) {
    const genderIndex = e.detail.value
    this.setData({
      genderIndex,
      'userInfo.gender': this.data.genders[genderIndex]
    })
  },

  onAgeInput(e) {
    this.setData({
      'userInfo.age': parseInt(e.detail.value)
    })
  },

  onHeightInput(e) {
    this.setData({
      'userInfo.height': parseFloat(e.detail.value)
    })
  },

  onWeightInput(e) {
    this.setData({
      'userInfo.weight': parseFloat(e.detail.value)
    })
  },

  onGoalChange(e) {
    this.setData({
      goalIndex: e.detail.value,
      'userInfo.goal': this.data.goals[e.detail.value]
    })
  },

  onDietaryRestrictionsChange(e) {
    const values = e.detail.value
    const restrictions = this.data.dietaryRestrictions.map(item => ({
      ...item,
      checked: values.includes(item.value)
    }))
    
    this.setData({
      dietaryRestrictions: restrictions,
      'userInfo.dietaryRestrictions': values
    })
  },

  async handleSave() {
 
      wx.showLoading({ title: '保存中' })
      
      const { userInfo, dietaryRestrictions } = this.data
      const selectedRestrictions = dietaryRestrictions
        .filter(item => item.checked)
        .map(item => item.value)
      
      // 转换性别为后端值
      const data = {
        ...userInfo,
        gender: GENDER_MAP[userInfo.gender] || 'other',
        dietaryRestrictions: selectedRestrictions
      }
      
      const res = await put('/users/profile', data)
      console.log(res,GENDER_MAP_REVERSE[res.gender] )
      {
     
        
        wx.showToast({
          title: '保存成功',
          icon: 'success'
        })
        
        // 更新全局用户信息
        const app = getApp()
        app.globalData.userInfo = res
        
        setTimeout(() => {
          wx.navigateBack()
        }, 1500)
      } 
    
   
  }
}) 